package com.velvetantler.weather.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.velvetantler.weather.R
import com.velvetantler.weather.bean.CityInfo

class CityListAdapter(val data: List<CityInfo>) :
    RecyclerView.Adapter<CityListAdapter.ViewHolder>() {

    /**
     * 点击事件监听接口
     */
    interface OnClickListener {
        fun onClick(position: CityInfo)
    }

    /**
     * 点击事件监听器
     */
    private var listener: OnClickListener? = null
    fun setOnClickListener(listener: OnClickListener) {
        this.listener = listener
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): ViewHolder {
        return ViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.item_city_list, parent, false)
        )
    }

    @SuppressLint("ResourceAsColor")
    override fun onBindViewHolder(
        holder: ViewHolder,
        position: Int
    ) {
        if (position == 0) {
            holder.view.findViewById<ImageView>(R.id.iv_location).visibility = View.VISIBLE
        }
        holder.view.findViewById<TextView>(R.id.tv_city_name).text = data[position].cityName

        // 点击事件
        holder.view.setOnClickListener {
            listener?.onClick(data[position])
        }
    }

    override fun getItemCount(): Int {
        return data.size
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val view = itemView.findViewById<View>(R.id.city_list_item)
    }
}